<?php
namespace App\Http\Controllers\Api;

use Encore\Admin\Grid\Filter\In;
use Illuminate\Http\Request;
use App\Models\Books;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Jobs\ChapterUpdateQueue;

class ListController extends Controller{

    protected $page;
    protected $pageSize;

    function __construct()
    {
        $this->page = Input::get('page',1);
        $this->pageSize = Input::get('pageSize',10);
    }

    /*
    * 获取小说列表
    * @param string type 类型
    * @param string orderBy 参数
    * return array $data 返回数据
    */
    public function bookList(){
        $type = Input::get('type');
        $updateDay = Input::get('updateDay');
        $isOver = Input::get('isOver');
        $orderBy= Input::get('orderBy',1);

        $where = [];
        $order = [];
        if (!empty($type)){
            $where['type'] = (int)$type;
        }
        if (!empty($updateDay)){
            $where['updated_at'] = array('>=',date('Y-m-d H:i:s',strtotime("- {$updateDay}day")));
        }
        if (!empty($isOver)){
            $where['is_over'] = $isOver;
        }
        if ($orderBy != 1){
            $order['sort'] = 'asc';
        }

        $data = Books::getBookList($where,[],$order);

        return jsonSuccessData($data);
    }

    /*
    * 小说章节列表
    * @param int id 小说ID
    * return array $data 返回数据
    */
    function chapterList(){
        $bookId = Input::get('id');
        $orderBy = Input::get('orderBy',1);
        if ($bookId == 0){
            return jsonErrorData('INVALID_PARAM');
        }
        /*最新章节列表*/
        $chapter_tableName = chapterTableNameByBookId($bookId);
        /*章节列表*/
        $data = DB::table($chapter_tableName)
            ->select(['id','book_id','title','created_at'])
            ->whereBook_id($bookId)
            ->when($orderBy,function ($query) use ($orderBy){
                if($orderBy == 1){
                    $query->orderBy('sort','asc');
                }else{
                    $query->orderBy('sort','desc');
                }
            })
            ->paginate($this->pageSize);

        //若该小说无章节则异步抓取章节数据
        $key = config('cacheKey.isUpdateBook').$bookId;
        if ($data->isEmpty() && !Redis::exists($key)){
            //设置锁，避免重复加入更新队列
            Redis::setex($key,3*86400,date('Y-m-d H:i:s'));
            ChapterUpdateQueue::dispatch(['id' => $bookId])->onQueue(config('cacheKey.chapterUpdateList'));
        }

        return jsonSuccessData($data);
    }

    /*
    * 小说所有章节列表(无分页)
    * @param int id 小说ID
    * return array $data 返回数据
    */
    function chapterAllList(){
        $bookId = Input::get('id');
        if ($bookId == 0){
            return jsonErrorData('INVALID_PARAM');
        }
        $key = config('cacheKey.chapterList').$bookId;
        $chapterList = Redis::get($key);
        if (empty($chapterList)){
            /*最新章节列表*/
            $chapter_tableName = chapterTableNameByBookId($bookId);
            /*章节列表*/
            $chapterList = DB::table($chapter_tableName)
                ->select(['id','book_id','title','created_at'])
                ->whereBook_id($bookId)
                ->orderBy('sort','asc')
                ->get();
            if (!empty($chapterList)){
                Redis::setex($key,86400*7,$chapterList);
            }else{
                Redis::setex($key,30,$chapterList);
            }
        }else{
            $chapterList = json_decode($chapterList,true);
        }

        return jsonSuccessData(['chapterList'=>$chapterList??[]]);
    }

    /*
    * 搜索小说
    * @param string keyword 输入内容
    * @return array
    */
    public function search(){
        $keyword = Input::get('keyword');
        $pageSize = Input::get('pageSize',30);

        if (!empty($keyword)){
            /*模糊查询 ，按关键词匹配度排序*/
            $where = [
                array('raw',"locate('$keyword', `name`)>0 OR locate('$keyword', `writer`)>0"),
            ];
            $order = [
                array('raw',"LENGTH(name),LENGTH(writer)"),
            ];
            $data = Books::getBookList($where,[],$order,false,$pageSize);

        }else{
            /*推荐*/
            $data = Books::getBookList([],[],[],false,$pageSize);
        }

        return jsonSuccessData($data);
    }


    /*
    * 最近搜索历史
    */
    public function searchList(){
        /*模糊查询 ，按关键词匹配度排序*/
        $data = [];

        return jsonSuccessData($data);
    }
}